//
//  TeacherDetailViewController.m
//  huashiedu
//
//  Created by oceans on 2018/9/1.
//  Copyright © 2018年 hema. All rights reserved.
//

#import "TeacherDetailViewController.h"
#import <UIImageView+WebCache.h>
#import <HCSStarRatingView.h>
#import "ClassListTableViewCell.h"
#import "ClassModel.h"
#import "TeacherDetailTableHeaderView.h"
#import "HttpRequest.h"
#import "NormalWebViewController.h"
#import "TeacherDetailImageTableViewCell.h"
#import <MJRefresh.h>
#import "SDPhotoBrowser.h"

@interface TeacherDetailViewController () <UITableViewDelegate, UITableViewDataSource, TeacherDetailTableHeaderViewDelegate, SDPhotoBrowserDelegate>

@property (strong, nonatomic) UITableView *tableview;
@property (strong, nonatomic) NSMutableArray <ClassModel *> *classArr;
@property (strong, nonatomic) NSMutableArray <NSString *> *imagesArr;
@property (strong, nonatomic) UILabel *titleLabel;
@property (strong, nonatomic) UIButton *focusButton;
@property (assign, nonatomic) int selectIndex;
@property (strong, nonatomic) MetaModel *model;
@end

@implementation TeacherDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self setupView];
    [self loadData];
}

- (void)loadData {
    
    self.classArr = [NSMutableArray array];
    __weak typeof(self) weakself = self;
    [HttpRequest getURL:kteacher_class paras:@{@"id": [NSNumber numberWithInt:_teacher._id]} showProgress:NO successful:^(id  _Nullable result) {
        
        for (NSDictionary *dic in result[@"data"][@"items"]) {
            ClassModel *model = [[ClassModel alloc] initWithDic:dic];
            [weakself.classArr addObject:model];
        }
        MetaModel *model = [[MetaModel alloc] initWithDic:result[@"meta"]];
        weakself.model = model;
        if (model.currentPage == model.pageCount || model.pageCount == 0) {
            if (weakself.selectIndex == 1) {
                [weakself.tableview reloadData];
                [weakself.tableview.footer endRefreshingWithNoMoreData];
            }
        }
    } failed:nil];
}

- (void)loadMoreData {
    
    __weak typeof(self) weakself = self;
    [HttpRequest getURL:kteacher_class paras:@{@"id": [NSNumber numberWithInt:_teacher._id], @"page": [NSNumber numberWithInt:self.model.currentPage + 1]} showProgress:NO successful:^(id  _Nullable result) {
        
        for (NSDictionary *dic in result[@"data"][@"items"]) {
            ClassModel *model = [[ClassModel alloc] initWithDic:dic];
            [weakself.classArr addObject:model];
        }
        MetaModel *model = [[MetaModel alloc] initWithDic:result[@"meta"]];
        weakself.model = model;
        if (model.currentPage == model.pageCount || model.pageCount == 0) {
            if (weakself.selectIndex == 1) {
                [weakself.tableview reloadData];
                [weakself.tableview.footer endRefreshingWithNoMoreData];
            }
        }else {
            if (weakself.selectIndex == 1) {
                [weakself.tableview.footer endRefreshing];
            }
        }
    } failed:^(int code, NSString *errMsg) {
        if (weakself.selectIndex == 1) {
            [weakself.tableview.footer endRefreshing];
        }
    }];
}

- (void)setupView {
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.imagesArr = [NSMutableArray arrayWithArray:_teacher.certs];
    
    self.focusButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_focusButton setTitleColor:COLOR(255, 96, 70, 1) forState:UIControlStateNormal];
    _focusButton.titleLabel.font = [UIFont systemFontOfSize:11.0];
    _focusButton.frame = CGRectMake(0, 0, 60, 20);
    _focusButton.layer.cornerRadius = 10.0;
    _focusButton.layer.borderColor = [UIColor colorWithRed:1.0 green:96/255.0 blue:70/255.0 alpha:1.0].CGColor;
    _focusButton.layer.borderWidth = 0.5;
    [_focusButton setTitle:@"+ 关注" forState:UIControlStateNormal];
    [_focusButton setTitle:@"已关注" forState:UIControlStateSelected];
    _focusButton.selected = _teacher.followed;
    [_focusButton addTarget:self action:@selector(focusButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    UIView *view = [[UIView alloc] initWithFrame:_focusButton.bounds];
    [view addSubview:_focusButton];
    UIBarButtonItem *right = [[UIBarButtonItem alloc] initWithCustomView:view];
    self.navigationItem.rightBarButtonItem = right;
    
    self.tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, XNavigationHeight, ScreenWidth, ScreenHeight - XNavigationHeight) style:UITableViewStylePlain];
    _tableview.delegate = self;
    _tableview.dataSource = self;
    _tableview.separatorInset = UIEdgeInsetsMake(0, 10, 0, 0);
    [_tableview registerNib:[UINib nibWithNibName:@"ClassListTableViewCell" bundle:nil] forCellReuseIdentifier:@"ClassListTableViewCell"];
    [_tableview registerClass:[TeacherDetailTableHeaderView class] forHeaderFooterViewReuseIdentifier:@"TeacherDetailTableHeaderView"];
    [_tableview registerNib:[UINib nibWithNibName:@"TeacherDetailImageTableViewCell" bundle:nil] forCellReuseIdentifier:@"TeacherDetailImageTableViewCell"];
    _tableview.tableFooterView = [UIView new];
    [self.view addSubview:_tableview];
    
    [self createTableviewHeaderView];
}

- (void)createTableviewHeaderView {
    
    UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 300)];
    header.backgroundColor = COLOR(245, 245, 245, 1);
    
    UIView *backview = [[UIView alloc] initWithFrame:header.bounds];
    backview.backgroundColor = [UIColor whiteColor];
    
    UIImageView *imageview = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
    imageview.layer.cornerRadius = 50.0;
    imageview.layer.masksToBounds = YES;
    imageview.layer.borderColor = [UIColor colorWithRed:239/255.0 green:243/255.0 blue:249/255.0 alpha:1.0].CGColor;
    imageview.layer.borderWidth = 6.0;
    [imageview sd_setImageWithURL:[NSURL URLWithString:_teacher.avatar]];
    imageview.center = CGPointMake(ScreenWidth * 0.5, 65);
    [backview addSubview:imageview];
    
    UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(imageview.frame) + 10, ScreenWidth, 21)];
    nameLabel.textAlignment = NSTextAlignmentCenter;
    [backview addSubview:nameLabel];
    NSMutableAttributedString *name = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@ ", _teacher.name] attributes:@{NSFontAttributeName: [UIFont boldSystemFontOfSize:15.0], NSForegroundColorAttributeName: [UIColor colorWithRed:63/255.0 green:63/255.0 blue:63/255.0 alpha:1.0]}];
    NSTextAttachment *attach = [[NSTextAttachment alloc] init];
    if (_teacher.gender == 0) {
        attach.image = nil;
    }else if (_teacher.gender == 1) {
        attach.image = [UIImage imageNamed:@"gender_m"];
    }else {
        attach.image = [UIImage imageNamed:@"gender_f"];
    }
    attach.bounds = CGRectMake(0, -3, 14, 14);
    [name appendAttributedString:[NSAttributedString attributedStringWithAttachment:attach]];
    nameLabel.attributedText = name;
    
    UILabel *nationLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(nameLabel.frame) + 4, ScreenWidth, 21)];
    nationLabel.textAlignment = NSTextAlignmentCenter;
    nationLabel.font = [UIFont systemFontOfSize:12.0];
    nationLabel.textColor = COLOR(109, 109, 109, 1);
    nationLabel.text = [NSString stringWithFormat:@"%@  |  %@", _teacher.nation, _teacher.birthday];
    [backview addSubview:nationLabel];
    
    CGFloat starWidth = 11 * _teacher.grade + (_teacher.grade - 1)*4;
    CGRect starFrame = CGRectMake((ScreenWidth - starWidth) * 0.5, CGRectGetMaxY(nationLabel.frame) + 9, starWidth, 11);
    HCSStarRatingView *starView = [[HCSStarRatingView alloc] initWithFrame:starFrame];
    starView.maximumValue = _teacher.grade;
    starView.tintColor = COLOR(255, 108, 96, 1);
    starView.starBorderWidth = 0;
    starView.spacing = 4;
    starView.value = _teacher.grade;
    starView.userInteractionEnabled = NO;
    [backview addSubview:starView];
    
    UIView *itemView = [[UIView alloc] initWithFrame:CGRectMake(45, CGRectGetMaxY(starView.frame) + 15, ScreenWidth - 90, 27)];
    itemView.backgroundColor = [UIColor whiteColor];
    
    UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 65, 27)];
    title.font = [UIFont systemFontOfSize:12.0];
    title.textColor = COLOR(51, 51, 51, 1);
    title.text = @"教学分类：";
    [itemView addSubview:title];
    
    int yLevel = 0;
    CGRect lastFrame = CGRectZero;
    for (NSInteger i = 0; i < _teacher.scopes.count; i ++) {
        
        NSString *tip = _teacher.scopes[i];
        CGRect tipRect = [tip boundingRectWithSize:CGSizeMake(ScreenWidth - 90, 17) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:12.0]} context:nil];
        UILabel *label = [[UILabel alloc] init];
        label.font = [UIFont systemFontOfSize:12.0];
        label.textColor = COLOR(128, 128, 128, 1);
        label.backgroundColor = COLOR(247, 247, 247, 1);
        label.layer.cornerRadius = 13.5;
        label.layer.masksToBounds = YES;
        label.textAlignment = NSTextAlignmentCenter;
        label.text = tip;
        if (i == 0) {
            label.frame = CGRectMake(CGRectGetMaxX(title.frame), 0, tipRect.size.width + 20, 27);
        }else {
            if (CGRectGetMaxX(lastFrame) + 10 + tipRect.size.width + 20 > ScreenWidth - 90) {
                yLevel ++;
                label.frame = CGRectMake(CGRectGetMaxX(title.frame), yLevel * (27 + 10), tipRect.size.width + 20, 27);
            }else {
                label.frame = CGRectMake(CGRectGetMaxX(lastFrame) + 10, yLevel * (27 + 10), tipRect.size.width + 20, 27);
            }
        }
        lastFrame = label.frame;
        [itemView addSubview:label];
        if (i == _teacher.scopes.count - 1) {
            itemView.frame = CGRectMake(45, itemView.frame.origin.y, ScreenWidth - 90, CGRectGetMaxY(label.frame));
        }
    }
    [backview addSubview:itemView];
    
    CGRect descriRect = [[NSString stringWithFormat:@"简介：%@", _teacher.teacherDescription] boundingRectWithSize:CGSizeMake(ScreenWidth - 90, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:12.0]} context:nil];
    UILabel *descriptionLabel = [[UILabel alloc] initWithFrame:CGRectMake(45, CGRectGetMaxY(itemView.frame) + 10, ScreenWidth - 90, descriRect.size.height)];
    descriptionLabel.numberOfLines = 0;
    NSMutableAttributedString *description = [[NSMutableAttributedString alloc] initWithString:@"简介：" attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:12.0], NSForegroundColorAttributeName: [UIColor colorWithRed:50/255.0 green:50/255.0 blue:50/255.0 alpha:1]}];
    NSAttributedString *appendStr = [[NSAttributedString alloc] initWithString:_teacher.teacherDescription attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:12.0], NSForegroundColorAttributeName: [UIColor colorWithRed:142/255.0 green:142/255.0 blue:142/255.0 alpha:1.0]}];
    [description appendAttributedString:appendStr];
    descriptionLabel.attributedText = description;
    [backview addSubview:descriptionLabel];
    backview.frame = CGRectMake(0, 0, ScreenWidth, CGRectGetMaxY(descriptionLabel.frame) + 25);
    [header addSubview:backview];
    header.frame = CGRectMake(0, 0, ScreenWidth, backview.frame.size.height + 10);
    _tableview.tableHeaderView = header;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 42.0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    TeacherDetailTableHeaderView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"TeacherDetailTableHeaderView"];
    view.delegate = self;
    return view;
}

- (void)tableHeaderButtonsPressed:(UIButton *)sender {
    
    if (sender.tag == 0) {
        
        _selectIndex = 0;
        [_tableview reloadData];
        if (_tableview.footer.isRefreshing) {
            [_tableview.footer endRefreshing];
        }
        _tableview.footer = nil;
    }else {
        _selectIndex = 1;
        [_tableview reloadData];
        _tableview.footer = [MJRefreshAutoStateFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
        if (_model != nil) {
            if (_model.currentPage == _model.pageCount) {
                [_tableview.footer endRefreshingWithNoMoreData];
            }
        }
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (_selectIndex == 0) {
        return _imagesArr.count;
    }
    return _classArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (_selectIndex == 0) {
        return ScreenWidth / 3.0 * 2.0;
    }
    
    const CGFloat height = (ScreenWidth - 20.0) * 0.39 * 0.586 + 32;
    return height;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (_selectIndex == 0) {
        
        TeacherDetailImageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TeacherDetailImageTableViewCell"];
        return cell;
    }
    
    static NSString *identity = @"ClassListTableViewCell";
    ClassListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identity forIndexPath:indexPath];
    return cell;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (_selectIndex == 0) {
        
        TeacherDetailImageTableViewCell *tcell = (TeacherDetailImageTableViewCell *)cell;
        [tcell.certImageview sd_setImageWithURL:[NSURL URLWithString:_imagesArr[indexPath.row]]];
    }else {
        ClassListTableViewCell *ccell = (ClassListTableViewCell*)cell;
        ClassModel *model = _classArr[indexPath.row];
        [ccell.classImageView sd_setImageWithURL:[NSURL URLWithString:model.thumb]];
        ccell.titleLabel.text = model.name;
        ccell.teacherLabel.text = model.teacher;
        ccell.timeLabel.text = model.begintime;
        NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"￥ " attributes:@{NSForegroundColorAttributeName: [UIColor colorWithRed:1.0 green:0 blue:54/255.0 alpha:1.0], NSFontAttributeName: [UIFont systemFontOfSize:10.0]}];
        NSAttributedString *price = [[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"%.2f", model.price] attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:12.0]}];
        [string appendAttributedString:price];
        ccell.priceLabel.attributedText = string;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (_selectIndex == 1) {
        NormalWebViewController *controller = [[NormalWebViewController alloc] init];
        controller.url = _classArr[indexPath.row].link;
        [self.navigationController pushViewController:controller animated:YES];
    }else {
        
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        SDPhotoBrowser *browser = [[SDPhotoBrowser alloc] init];
        browser.sourceImagesContainerView = cell;
        browser.imageCount = self.imagesArr.count;
        browser.currentImageIndex = indexPath.row;
        browser.delegate = self;
        [browser show];
    }
}

- (UIImage *)photoBrowser:(SDPhotoBrowser *)browser placeholderImageForIndex:(NSInteger)index {
    return nil;
}

- (NSURL *)photoBrowser:(SDPhotoBrowser *)browser highQualityImageURLForIndex:(NSInteger)index {
    
    return [NSURL URLWithString:_imagesArr[index]];
}

- (void)focusButtonPressed {
    
    __weak typeof(self) weakself = self;
    [_teacher focusTeacher:^{
        weakself.focusButton.selected = !weakself.focusButton.selected;
    } failed:^{
        
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

@end
